package com.didi.gulimall.aop;


import com.didi.gulimall.common.constant.RabbitMqConstant;
import com.didi.gulimall.common.entity.LocalMqEntity;
import com.didi.gulimall.coupon.dao.LocalMqDao;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author 10626
 * @Create 2021/6/3 20:20
 */
@Aspect
@Component
@Slf4j
public class MqLogAspect {

    @Autowired
    private LocalMqDao localMqDao;

    @Autowired
    private ThreadPoolExecutor executor;

    //定义切入点，使用了该注解的方法将被AOP切入
    @Pointcut("@annotation( com.didi.gulimall.aop.MqLog)")
    public void logPointCut() {
    }

    /**
     * @param joinPoint
     * @return
     */
    @Before("logPointCut()")
    public void logBefore(JoinPoint joinPoint) throws JsonProcessingException {
        CompletableFuture.runAsync(() -> {
            log.info("目标方法：" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.info("传入参数：" + Arrays.toString(joinPoint.getArgs()));
            Object[] args = joinPoint.getArgs();
            LocalMqEntity localMqEntities = (LocalMqEntity) args[0];
            localMqEntities.setStatus(RabbitMqConstant.NOT_CONSUMED);
            localMqEntities.setCreatedTime(new Date());
            localMqDao.insert(localMqEntities);
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            MqLog annotation = method.getAnnotation(MqLog.class);
        });
    }
}
